<!-- 权限列表 -->
<template>
  <div>
    <div class="detail_box">
      <!-- 操作 -->
      <div class="operate_box">
        <div class="item_box">
          <div class="operate_item">
            <label>权限名称：</label>
            <el-input type="text" placeholder="请输入权限名称" v-model="keyword"></el-input>
          </div>
          <div class="operate_item">
            <label>父级：</label>
            <el-select
              filterable
              @change="getParentMenu($event,1)"
              v-model="first"
              placeholder="请选择一级菜单">
              <el-option
                v-for="(item,index) in firstSelect"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="operate_item" v-if="first">
            <el-select
              filterable
              v-model="second"
              placeholder="请选择二级菜单">
              <el-option
                v-for="(item,index) in secondSelect"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="operate_item">
            <label>状态：</label>
            <el-select
              filterable
              v-model="status"
              placeholder="请选择状态">
              <el-option
                v-for="(item,index) in statusOptions"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="operate_item">
            <span class="operate_btn search_btn" @click="getTableInfo">查询</span>
            <span class="operate_btn reset_btn" @click="resetTable">重置</span>
          </div>
        </div>
        <div class="btn_box" v-if="btn&&(btn.add||btn.import||btn.export)">
          <span class="operate_btn search_btn" @click="openPopup('')" v-if="btn.add">新增</span>
          <el-upload ref="upload" class="avatar-uploader"
                     :action="uploadUrl"
                     v-show="btn.import"
                     :headers="{token:token}"
                     :data="param"
                     accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                     :show-file-list="false"
                     :on-success="importSuccess">
            <el-button type="success" class="operate_btn import_btn">导入</el-button>
          </el-upload>
          <span class="operate_btn export_btn" @click="isExport=true" v-if="btn.export">导出</span>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table_box">
        <el-table
          border
          v-loading="loading"
          :header-cell-style="tableHeader"
          ref="multipleTable"
          :data="tableInfo"
          tooltip-effect="dark"
          row-key="id"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          style="width: 100%;">
          <el-table-column
            width="120"
            prop="id"
            label="ID">
          </el-table-column>
          <el-table-column
            sortable
            prop="modifyTime"
            width="160"
            label="修改时间">
            <template slot-scope="scope">
              <p style="text-align: left">{{ formatTime(scope.row.modifyTime) }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="菜单名称">
          </el-table-column>
          <el-table-column
            label="路径">
            <template slot-scope="scope">
              <span>{{ scope.row.url ? scope.row.url : '——' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="备注">
            <template slot-scope="scope">
              <span>{{ scope.row.memo ? scope.row.memo : '——' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            label="状态">
            <template slot-scope="scope">
              <span class="normal" :class="{'unusual':scope.row.enable===0}">{{ scope.row.enable ? '可用' : '禁用' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            v-if="btn&&(btn.update||btn.delete)"
            width="150">
            <template slot-scope="scope">
              <div class="table_btn">
                <span class="change_info" @click="openPopup(scope.row.id)" v-if="btn.update">编辑</span>
                <span class="change_info delete_btn" @click="deleteItem(scope.row)" v-if="btn.delete">删除</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <edit :mid="menuId" v-if="isPop" @listenToChild="listenToEdit"></edit>
    <importData v-if="isImport" :data="importData" @listenToChild="isImport=false"></importData>
    <exportData v-if="isExport" @listenToChild="isExport=false"></exportData>
  </div>
</template>

<script>

import edit from "./edit";
import exportData from "./exportData";
import importData from "@/components/importData";
import commons from "@/utils/common";
import {restUrl} from '../../../../url'
import {getBtn} from "@/utils/btnAuth";
import {listData, delData, getSelect} from "../../../api/permission";
import {getWebMenu} from "../../../api/permission";
import {setTree} from "../../../utils/menuAuth";
import {getPlatformCode} from "../../../utils/code";
import {getToken} from "../../../utils/auth";

export default {
  components: {
    exportData,
    importData,
    edit
  },
  data() {
    return {
      keyword: '',
      status: '',
      statusOptions: [{id: '', name: '全部'}, {id: 0, name: '禁用'}, {id: 1, name: '启用'}],
      first: '',
      second: '',
      firstSelect: [],
      secondSelect: [],
      loading: false,
      tableInfo: [],
      menuId: '',
      isPop: false,
      isExport: false,
      isImport: false,
      importData: {},
      uploadUrl: restUrl + '/sys/permission/excel/import',
      token: getToken(),
      param: {folder: 'web/limit'},
      btn: {},
    }
  },
  mounted() {
    this.getParentMenu(0, 0);
    getBtn().then(res=>{
      this.btn = res;
      if (this.btn.query) {
        this.getTableInfo(1);
      }
    })
  },
  methods: {
    // 获取列表
    getTableInfo() {
      let that = this;
      that.loading = true;
      let queryParams = {
        name: that.keyword,
        enable: that.status,
        parentId: (that.second ? that.second : (that.first ? that.first : '')),
        platformCode:getPlatformCode(),
        memo: '',
        type: ''
      }
      listData(queryParams).then(res => {
        that.tableInfo = res.data ? that.handleTree(res.data) : [];
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },

    // 重置
    resetTable() {
      this.keyword = '';
      this.status = '';
      this.second = '';
      this.first = '';
      this.secondSelect = [];
      this.getTableInfo()
    },

    // 获取父级菜单，0一级菜单 -1 连级菜单 其他 二级菜单
    getParentMenu(id, type) {
      let that = this;
      let param = {
        parentId: id
      }
      getSelect(param).then(res => {
        if (res.data) {
          that.setMenu(type, res.data);
        } else {
          that.setMenu(type, []);
        }
      }).catch((e) => {
      });
    },

    // 设置一二级菜单索引
    setMenu(type, data) {
      let that = this;
      if (type === 0) {
        that.firstSelect = data;
      } else {
        that.second = '';
        that.secondSelect = data;
      }
    },

    // 移除
    deleteItem(obj) {
      let that = this;
      that.$confirm('确定删除「' + obj.name + '」权限信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delData(obj.id).then((res)=>{
          if (res.success) {
            that.getTableInfo(that.currentPage);
            that.getLeftMenu();
            that.$message.success('删除成功！');
          }
        })
      }).catch(() => {
        // console.product('fail')
      });
    },

    getLeftMenu(){
      getWebMenu({type: 1,platformCode:getPlatformCode()}).then((res) => {
        if (res.data) {
          setTree(JSON.stringify(res.data))
        }
      })
    },

    // 打开弹窗
    openPopup(id) {
      this.isPop = true;
      this.menuId = id;
    },

    // 监听弹窗关闭
    listenToEdit(e) {
      this.isPop = false;
      if (e.refresh) {
        this.getTableInfo()
      }
    },

    // excel导入
    importSuccess(res) {
      if (res.success) {
        if (res.data.failedCount) {
          this.isImport = true;
          this.importData = res.data
        } else {
          this.$message.success({
            message: '全部导入成功！',
            duration: 1500
          });
        }
      } else {
        this.$message.error({
          message: res.message,
          duration: 1500
        })
      }
    },

    // 时间格式化
    formatTime(time) {
      return commons.formatTime(time)
    },

    // 设置table标题居中
    tableHeader({row, column, rowIndex, columnIndex}) {
      return 'background:#F0F2F5;color:#111;padding:10px 0;font-size:14px;font-weight:600;'
    },
  }
}
</script>

<style scoped>

</style>
